const app = getApp();
const req = require("../../utils/http.js");
Page({
  data: {
    display:'block',
    senShow:false,
    product:[],
    merchant:'',
    currentTab:'' ,
    setShow:false,
    address:'',
    merchants:'',
    send_coupon_params:[],
    ticketType:'',
    doSignValue:'',
    outTradeNo:''

  },
  //商品详情1
  getProductDetail(e){
    let t = this
    let params = {}
    let id = e
    let currentTab = t.data.currentTab //'0'(优惠卷)；'1'(商品)
    let setType = t.data.setType //新人礼跳转 0优惠劵  1商品
    let ticketType = t.data.ticketType //0：商品券 1：其他
    let url =''
    if (ticketType==0){ //商品券
      url =`/coupon/wxProduct/getBusinessCouponDetail/${id}`
    }else{
      if (currentTab == '1' || setType == '1') {
        url = `/coupon/wxProduct/getProductDetail/${id}`
      } else {
        url = `/coupon/wxProduct/getCouponDetail/${id}`
      }
    }
  
    req.http(url,"GET",params).then(res=>{
      if(res.data.code==200){
        t.setData({
          product:res.data.result,
          merchant: res.data.result.store,
          merchants: res.data.result.stores,
          currentTab,
        })
      }else{
        wx.showToast({
          title: res.data.message,
          icon:'none',
          duration:1000
        })
      }
    })
  },
  //
 
 // 商品购买
  receiveBuy(){
    let t = this
    let { productId, ticketType} = t.data
    let url=''
    if (ticketType==0){//商品券
      url ='/coupon/wxProduct/wxBusinessCouponPay'
    }else{//其他
      url ='/coupon/wxProduct/wxPay'
    }
    let setShow = t.data.setShow
    if (setShow == false && t.data.ticketType!=0){ //跳转地址页面
      wx.navigateTo({
        url: '../address/index',
      })
    }else{
      wx.showLoading({
        title: '购买中...',
        mask: true,
      })
   
      let address = t.data.address.data
      let params = {
        productId,
        address
      }
      req.wxReq(url,"POST", params).then(res => {
        wx.hideLoading();
        if(res.data.code==200){
          let outTradeNo = res.data.result.outTradeNo
          wx.requestPayment({
            timeStamp: res.data.result.timeStamp,
            nonceStr: res.data.result.nonceStr,
            package: res.data.result.packageValue,
            signType: 'MD5',
            paySign: res.data.result.paySign,
            success(res) {
              if (res.errMsg="requestPayment:ok"){
                let interval = setInterval(function () { t.getBuySuccess(outTradeNo) }, 1000);
                t.setData({
                  interval,
                  outTradeNo
                })
                wx.switchTab({
                  url: '../index/index',
                })
              }
            },
            fail(res) {
              console.log('失败',res)
            }
          })
         
        }
        else if(res.data.code == 7006){
          let appid = res.data.result.serviceAppId
          let setfrom = res.data.result.from
          let obj = 'wxPay'
          wx.showModal({
            content: res.data.message,
            success(res){
              if(res.confirm){
                  wx.navigateTo({
                    url: '../publicToken/index?productId=' + productId + '&appid=' + appid + '&setfrom=' + setfrom + '&obj=' + obj 
                  })
              }else if(res.cancel){
                wx.navigateBack({
                  delta: 1
                })
              }
            }

          })
        }
      })
    }

  },

  //商品券---查询购买商家券信息
  //GET /coupon/wxUser/getBuySuccess/{outTradeNo}
  getBuySuccess(e){
    let t = this
    req.wxReq(`/coupon/wxUser/getBuySuccess/${e}`, "GET").then(res => {
      console.log(res)
      let value = res.data.result
      let interval = t.data.interval
      let outTradeNo = t.data.outTradeNo
      if (res.data.code == 200) {
        clearInterval(interval);
        wx.navigateTo({
          url: '../sendCoupon/sendCoupon?value=' + value + '&outTradeNo=' + outTradeNo,
        })
      
      }else{
        wx.showToast({
          title: res.data.message,
          icon:'none',
          duration:800
        })
        setTimeout(() => {
          clearInterval(interval);
        }, 2000)
      }
    })
  },


  //领取优惠卷
  receiveCoupon(e){
    let t = this
    let productId = t.data.productId
    let params = {productId}
    req.wxReq('/coupon/wxProduct/receiveCoupon',"GET",params).then(res=>{    
      if(res.data.code==200){
        wx.showToast({
          title: res.data.message,
          icon: 'none',
          duration: 1000
        })
        setTimeout(()=>{
         wx.navigateBack({
           data:1
         })
        },1300)

      } else if (res.data.code == 7006){ //未授权
        let appid = res.data.result.serviceAppId
        let setfrom = res.data.result.from
        let obj = 'receiveCoupon'
        setTimeout(()=>{
          wx.navigateTo({
            url: '../publicToken/index?productId=' + productId + '&appid=' + appid + '&setfrom=' + setfrom + '&obj=' + obj ,
          })
        },1600)
     
      }else{
        wx.showToast({
          title: res.data.message,
          icon: 'none',
          duration: 1500
        })
      }
    })
  },

  //查看更多门店
  goMerchantList: function (e) {
    let t = this
    let currentTab = t.data.currentTab
    const productId = this.data.productId;  
    if (t.data.merchants.length){
      wx.navigateTo({
        url: '../merchantList/index?productId=' + productId
      })
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onShow(){
    let t = this
    wx.getStorage({
      key: 'address',
      success: function (res) {
        if(res){
          t.setData({
            address: res,
           setShow: true
          })

        }else{
          console.log('没有信息')
        }
      },
    })
  },
  onLoad: function (options) {
    let t = this
    let currentTab = options.currentTab
    let productId = options.productId
    let ticketType = options.ticketType //0 :商品代金券，1为其他
    //新人礼跳转 //0优惠劵  1商品
    let setType = options.setType
    this.setData({
      productId: options.productId,
      currentTab,
      setType,
      ticketType
    });
    t.getProductDetail(productId)
    wx.setNavigationBarTitle({
      title: wx.getStorageSync('appName'),
    })

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },


  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})
